import dayjs  from 'dayjs'
import { addNum, subNum, debounce } from 'shiptools'
import { INVOICE_NOTICES, INVOICE_TYPE, INVOICE_TITLE_TYPE, channel, SHIP_REG, TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants' 
import { STORAGE_KEY } from '../../utils/storage'
import { setPage } from '../../utils/index'
import { getOrderApi, getInvoiceDetailApi, getInvoiceDetailNewApi, getInvoiceTitleApi, getInvoiceHistoryTitleApi, invoiceDataChangeApi, invoiceDataChangeNewApi, queryRegionApi } from '../../api/index'
import { asyncToast, delay } from '../../utils/index'

import { cleanOrderData, invoiceFactory } from '../order/main'
import { showInvoiceTabs, invoiceForm, editForm, toggleForm, getCityList, getDistrictList } from './main'
const pageName = TRACER_PAGES['invoice']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    invoiceNotices: INVOICE_NOTICES,
    invoiceType: INVOICE_TYPE,
    invoiceTitleType: INVOICE_TITLE_TYPE,
    invoiceDetail: {},

    dateOfInvoice: '',
    invoiceList: [],

    invoiceTypes: [],

    isInvoiceOpen: true,

    currentInvoiceType: 0,
    isLoading: false,

    invoiceSearchResult: [],

    isListOpened: false,
    isCalculating: false,
    searchQueryIsDirty: false,

    titleList: [],
    isTyping: false,

    address: [],
    addressDetail: '',
    contact: '',
    mobile: '',
    preAddressRange: [],
    addressRange: [],
    preAddressIndexList: [-1, -1, -1],
    addressIndexList: [-1, -1, -1],
    addressObj: null,

    invoiceTips: '',
    invoiceTypeForShow: 1,
    
    invoiceTypeTextObj: {
      1: '电子发票',
      2: '纸质发票',
      3: '电子发票+纸质发票'
    },
    currentTab: 0,

    showTabs: false,
    forms: [],

    order: {},
    invoice: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init(options)
    setPage(pageName, PRODUCT_CODE)
  },

  init: function(query) {
    const that = this
    const { serialId, invoiceTips, invoiceTypeForShow } = query
        
    let mobile = wx.getStorageSync(STORAGE_KEY.mobile) || ''
    const emailStr = wx.getStorageSync(STORAGE_KEY.email) || ''
    const _invoiceTypes = Object.keys(INVOICE_TITLE_TYPE)
    this.setData({
      invoiceTypes: _invoiceTypes,
      invoiceTips,
      invoiceTypeForShow: invoiceTypeForShow? Number(invoiceTypeForShow): 1
    })

    that.getOrder(query).then(order => {
      that.getInvoiceDetail(order).then(response => {

        const {showTabs, currentTab} = showInvoiceTabs(response)
        invoiceForm(currentTab === 0, response, order, forms => {
          console.log("forms: ", forms)
          that.setData({
            showTabs,
            currentTab,
            forms,
            order,
            invoice: response
          })
        })
        
      })
    })
    
  },

  // picker确认
  bindMultiPickerChange (e) {
    const indexList = e.detail.value
    const pId = e.currentTarget.dataset.pid	
    const forms = this.data.forms
    const isLoading = this.data.isLoading

    if(indexList.includes(-1)) {
      console.log("地区有误")
      return
    }
    forms.forEach(currentForm => {
      if(currentForm.id === pId) {
        currentForm.addressIndexList = JSON.parse(JSON.stringify(indexList))
        currentForm.preAddressIndexList = JSON.parse(JSON.stringify(indexList))
        currentForm.preAddressRange = currentForm.addressRange && JSON.parse(JSON.stringify(currentForm.addressRange))
        console.log("currentForm: ", currentForm)
        if(currentForm.addressRange[0][currentForm.addressIndexList[0]] && currentForm.addressRange[1][currentForm.addressIndexList[1]] && currentForm.addressRange[2][currentForm.addressIndexList[2]]) {
          // if(!currentForm.addressRange[1][currentForm.addressIndexList[1]] !== currentForm.city) return
          const addressArea = currentForm.addressIndexList[0] === -1 ? '请选择' : `${currentForm.addressRange[0][currentForm.addressIndexList[0]].name} ${currentForm.addressRange[1][currentForm.addressIndexList[1]].name} ${currentForm.addressRange[2][currentForm.addressIndexList[2]].name}`
          const _forms = editForm([{pId, id: 7, eValue: addressArea}], forms)
          this.setData({
            forms: _forms
          })
        }
      }
    })
  },
  // picker列改变
  bindMultiPickerColumnChange (e) {
    const that = this
    const columnIndex = e.detail.column
    const index = e.detail.value
    const pId = e.currentTarget.dataset.pid	
    const forms = this.data.forms
   
    forms.forEach(currentForm => {
      if(currentForm.id === pId) {
        if(currentForm) {
          if (columnIndex === 0) {
            currentForm.addressIndexList = [index, 0, 0]
            const provinceId = currentForm.addressRange[0][index].id
            let districtId = 0
            getCityList(provinceId)
              .then(cityList => {
                if (cityList) {
                  currentForm.addressRange[1] = cityList
                  const cityId = cityList[0].id
                  getDistrictList(provinceId, cityId).then(districtList => {
                    currentForm.addressRange[2] = districtList
                    districtId = districtId || districtList[0].id
                    const cityIndex = cityList.findIndex(item => item.id === cityId)
                    const districtIndex = districtList.findIndex(item => item.id === districtId)
                    currentForm.addressIndexList = [index, cityIndex, districtIndex]

                    
                    const addressArea = currentForm.addressIndexList[0] === -1 ? '请选择' : `${currentForm.addressRange[0][currentForm.addressIndexList[0]].name} ${currentForm.addressRange[1][currentForm.addressIndexList[1]].name} ${currentForm.addressRange[2][currentForm.addressIndexList[2]].name}`

                    const _forms = editForm([{pId, id: 7, eValue: addressArea}], forms)
                    that.setData({
                      forms: _forms
                    })
                  })
                }
              })
          } else if (columnIndex === 1) {
            const provinceIndex = currentForm.addressIndexList[0]
            const provinceId = currentForm.addressRange[0][provinceIndex]
            const cityId = currentForm.addressRange[1][index].id
           
            currentForm.addressIndexList = [provinceIndex, index, 0]
            getDistrictList(provinceId, cityId).then(districtList => {
              currentForm.addressRange[2] = districtList
              const addressArea = currentForm.addressIndexList[0] === -1 ? '请选择' : `${currentForm.addressRange[0][currentForm.addressIndexList[0]].name} ${currentForm.addressRange[1][currentForm.addressIndexList[1]].name} ${currentForm.addressRange[2][currentForm.addressIndexList[2]].name}`

              const _forms = editForm([{pId, id: 7, eValue: addressArea}], forms)
              that.setData({
                forms: _forms
              })
            })
          }
        }
      }
    })

    // this.setData({
    //   forms
    // })
  },
  // picker取消
  bindMultiPickerCancel (e) {
    // 复原
    const that = this
    const pId = e.currentTarget.dataset.pid	
    const forms = this.data.forms
    
    forms.forEach(currentForm => {
      if(currentForm.id === pId) {
        currentForm.addressIndexList = JSON.parse(JSON.stringify(currentForm.preAddressIndexList))
        currentForm.addressRange = JSON.parse(JSON.stringify(currentForm.preAddressRange))

        const addressArea = currentForm.addressIndexList[0] === -1 ? '请选择' : `${currentForm.addressRange[0][currentForm.addressIndexList[0]].name} ${currentForm.addressRange[1][currentForm.addressIndexList[1]].name} ${currentForm.addressRange[2][currentForm.addressIndexList[2]].name}`

        const _forms = editForm([{pId, id: 7, eValue: addressArea}], forms)
        that.setData({
          forms: _forms
        })
      }
    })
    
  },

  getOrder: function({serialId}) {
    const that = this
    if(!serialId) return
    return getOrderApi({serialId}).then(response => {
      let orderDetail = cleanOrderData(response)

      
        // FIXME: test
        // orderDetail.orderStateName = '已出票'

      this.setData({
        orderDetail
      })
      return orderDetail
    })
  },

  getInvoiceDetail: function(orderDetail) {
    const {serialId, supplierId, totalAmount, totalPrice, ticketAllPrice, departureInfo} = orderDetail
    return getInvoiceDetailNewApi({
      supplierId,
      serialId
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      if(!response.data || !response.data.isSuccess) {
          return
      }

      let result = response.data.data

      return result
    })
  },

  onSearchInvoiceTitle: function(keyword) {
    const that = this
    return getInvoiceTitleApi({
      keyword
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      const result = response.data

      if(!result || result.code !== 200) {
        that.setData({
          invoiceSearchResult: []
        })
        return
      }
      const list = result.data.result
      that.setData({
        invoiceSearchResult: list
      })
    })
  },

  chooseInvoiceTitle: function(e) {
    const item = e.currentTarget.dataset.item

    if(!item) {
      this.setData({
        invoiceSearchResult: []
      })
      return
    }

    
    const pId = e.currentTarget.dataset.pid
    const { forms } = this.data
    const _forms = editForm([{pId, id: 4, eValue: item.name}, {pId, id: 5, eValue: item.creditCode}], forms)

    this.setData({
      forms: _forms,
      invoiceSearchResult: []
    })
  },

  onPickInvoiceType: function(e) {
    const item = e.currentTarget.dataset.item
    const id = e.currentTarget.dataset.id
    const pId = e.currentTarget.dataset.pid
    const canEdit = e.currentTarget.dataset.can
    if(!canEdit) return
    const { forms } = this.data
    const eValue = parseInt(item)
    const _forms = editForm([{pId, id, eValue}], forms)
    this.setData({
      forms: _forms
    })
  },
  onInvoiceTaxFocus: function(e) {},
  onInvoiceTaxBlur: function(e) {},
  onInvoiceTaxHandler: function(e) {
    const value = e.detail
    const invoiceDetail = this.data.invoiceDetail;
    if(!invoiceDetail.canEdit) {
        return
    }
    // this.props.onSelect('type', _toNumber(item))
    // const value = _toNumber(item)

    this.setData({
      invoiceTax: value
    })
  },
  onClearEmail: function() {
    this.setData({
      invoiceEmail: ''
    })
  },
  onClearTitle: function() {
    this.setData({
      invoiceTitle: ''
    })
  },
  onClearTax: function() {
    this.setData({
      invoiceTax: ''
    })
  },

  onClearAddressDetail: function() {
    this.setData({
      addressDetail: ''
    })
  },
  setInvoiceAddressDetail: function(e) {
    this.setData({
      addressDetail: e.detail
    })
  },
  onClearContact: function(e) {
    this.setData({
      contact: ''
    })
  },
  setInvoiceContact: function(e) {
    this.setData({
      contact: e.detail
    })
  },
  onClearMobile: function(e) {
    this.setData({
      mobile: ''
    })
  },
  setInvoiceMobile: function(e) {
    this.setData({
      mobile: e.detail
    })
  },

  showInvoiceDetail: function(e) {

    const invoicePrice = this.data.invoicePrice
    if(invoicePrice > 0) {
      this._openDetail()
    }

  },

  _openDetail: function() {
    const { invoiceList } = this.data;
    if(invoiceList && invoiceList.length > 0) {
        this.setData({
            isListOpened: true
        })
    }
  },

  onCloseInvoiceList: function() {
    this.setData({
        isListOpened: false
    })
  },

  onInvoiceEmailHandler: function(e) {
    const value = e.detail
    const invoiceDetail = this.data.invoiceDetail;
    if(!invoiceDetail.canEdit) {
        return
    }

    this.setData({
      invoiceEmail: value
    })

  },

  onInvoiceTitleBlur: function(e) {
    const that = this
    // e.stopPropagation()
    // e.preventDefault()
    // delay(300).then(() => {
    //     that.setData({
    //         isTyping: true
    //     }, () => {
    //         that.onBlur();
    //     })
    // })
  },


  invoiceDataChange: function(params) {
    return invoiceDataChangeNewApi(params)
  },
 
  // 发票表单校验
  checkInvoceForm(items) {
    let errMsg = []
    items.map(item => {
        if (item.required) {
            if (typeof item.value === 'string' && !item.value.trim() || item.value === '请选择') {
                item.msg = `请${item.id === 7? '选择': '填写'}${item.title || item.label}`
                errMsg.push(item)
            } else {

              let _reg = ''
              switch(item.id) {
                case 4:
                  break;
                case 5:
                  _reg = SHIP_REG.TAX
                  break;
                case 6:
                  _reg = SHIP_REG.EMAIL
                  break;
                case 10:
                  _reg = SHIP_REG.MOBILE
                  break;
                default:
                  break;
              }

              if(_reg && !_reg.test(item.value)) {
                item.msg = `${item.title || item.label}格式不合法`
                errMsg.push(item)
              }
            }
        }
    })
    return errMsg
  },

  findValById: function(id, list) {
    const result = list.find(item => item.id === id)
    if(!result) return ''

    return result.value
  },

  comfirmModifyInvoice: function(e) {
    const that = this
    const form = e.currentTarget.dataset.form
    console.log('form: ', form)
    
    // 发票配置
    const {
      orderDetail,
    } = this.data;
    const currentInvoiceType = that.findValById(3, form.list)
    const invoiceTitle =that.findValById(4, form.list)
    const invoiceTax = that.findValById(5, form.list)
    const invoiceEmail = that.findValById(6, form.list)
    const invoicePrice = that.findValById(2, form.list).replace(/¥/, '')
    const address = that.findValById(8, form.list)
    const contact = that.findValById(9, form.list)
    const mobile = that.findValById(10, form.list)

    if(!orderDetail) return;

    const invoiceErrMsg = this.checkInvoceForm(form.list)
    if(invoiceErrMsg.length > 0) {
        wx.showToast({
            title: invoiceErrMsg[0].msg,
            icon: 'none',
            duration: 2000
        })
        return
    }
    if(that.data.isLoading) {
      // 加载中
      return
    }
    that.setData({
      isLoading: true
    })


    let companyAddress = ''
    let addressShow = ''

    if (form.includePaperInvoice) {
      const provinceItem = form.addressRange[0][form.addressIndexList[0]]
      const cityItem = form.addressRange[1][form.addressIndexList[1]]
      const districtItem = form.addressRange[2][form.addressIndexList[2]]
      const addressObj = {
        provinceId: provinceItem.id,
        province: provinceItem.name,
        cityId: cityItem.id,
        city: cityItem.name,
        districtId: districtItem.id,
        district: districtItem.name,
        addressDetail: address
      }
      companyAddress = provinceItem.name + cityItem.name + districtItem.name + addressObj.addressDetail
      addressShow = JSON.stringify(addressObj)
    }
    that.invoiceDataChange({
        ApplyId: form.invoiceId || 0,
        titleType: currentInvoiceType,
        title: invoiceTitle,
        taxNo: invoiceTax,
        invoiceAmount: invoicePrice,
        applicantEmail: invoiceEmail,
        orderId: orderDetail.orderId,
        CompanyAddress: companyAddress,
        Bank: contact || '',
        TelNo: mobile || '',
        AddressShow: addressShow
    }).then(response => {
      
      if(!response || response.status !== 200) {
        that.setData({
          isLoading: false
        })
        return
      }
      const res = response.data
      if(!res.isSuccess) {
          wx.showToast({
              title: '申请开票失败，请稍后再试',
              icon: 'none',
              duration: 2000
          })
          that.setData({
            isLoading: false
          })
          return
      }

      asyncToast({
          title: '申请成功',
          icon: 'success',
          duration: 2000
      }).then(() => {

        // FIXME: 判断是否在未申请tab里
        const _currentTab = this.data.currentTab
          that.getInvoiceDetail(orderDetail).then(response => {
            const {showTabs, currentTab} = showInvoiceTabs(response)
            invoiceForm(currentTab === 0, response, orderDetail, forms => {
              if(_currentTab === 0 && forms.length > 1) {
                console.log("forms: ", forms)
                that.setData({
                  showTabs,
                  currentTab,
                  forms,
                  order: orderDetail,
                  invoice: response,
                  isLoading: false
                })
              } else {
                wx.navigateBack();
                that.setData({
                  isLoading: false
                })
              }
            })
            
          })
      })
    
    })
  },

  onInvoiceTitleFocus: function(e) {
    const that = this
    const memberId = wx.getStorageSync(STORAGE_KEY.memberId)
    const titleName = ['company', 'personal', 'office']
    const currentInvoiceType = this.data.currentInvoiceType
    return getInvoiceHistoryTitleApi({
      id: memberId,
      channel: channel,
      invoiceType: currentInvoiceType
    }).then(response => {
      if(!response || response.status !== 200) {
        return
      }
      const data = response.data
      if(!data || data.code !== 10000) {
        return
      }
      const result = data.data
     
      Object.keys(result).forEach(function (type) {
          result[type].forEach(function (item, index) {
              result[type][index] = {
                  creditCode: item.taxpayerNum,
                  name: item.invoiceTitle
              }
          })
      })

      that.setData({
        invoiceSearchResult: result[titleName[currentInvoiceType]],
        isCalculating: false,
        searchQueryIsDirty: false,
        isTyping: false
    })
    })
  },


  onInvoiceTitleHandler: debounce(function(e) {
    const that = this;
    const eValue = e.detail
    const id = e.currentTarget.dataset.id
    const pId = e.currentTarget.dataset.pid
    const { forms } = this.data
    if(!eValue) {
      this.setData({
        invoiceSearchResult: []
      })
      return
    }
    forms.forEach(item => {
      if(pId === item.id) {
        const invoiceTypeItems = item.list.filter(item => item.id === 3)[0]
        const currentInvoiceType = invoiceTypeItems? invoiceTypeItems.value: 0
        const _forms = editForm([{pId, id, eValue}], forms)
        this.setData({
          forms: _forms
        })
        const { isTyping } = this.data;
        if(currentInvoiceType !== 0) {
          const _forms = editForm([{pId, id: 4, eValue}, {pId, id: 5, eValue: ''}], forms)
          this.setData({
            forms: _forms,
            invoiceSearchResult: []
          })
          return;
        }
        
        if(!isTyping) {
            that.setData({
                searchQueryIsDirty: true
            })
            if(eValue) {
                that.setData({
                    isCalculating : true,
                })
                that.onSearchInvoiceTitle(eValue).then(data => {
                    that.setData({
                        isCalculating: false,
                        searchQueryIsDirty: false
                    })
                })
        
            }
        }
      }
    })

  }, 500),


  onTabHandle: function(e) {
    const that = this
    const { invoice, order, currentTab } = this.data
    const index = e.currentTarget.dataset.index
    if(currentTab === index) return
    this.setData({
      currentTab: index
    })
    invoiceForm(index === 0, invoice, order, forms => {
      that.setData({
        forms
      })
    })
  },

  onClearInput: function(e) {
    console.log("onClearInput: ", e)
    const id = e.currentTarget.dataset.id
    const pId = e.currentTarget.dataset.pid
    const { forms } = this.data
    const _forms = editForm([{pId, id, eValue: ''}], forms)
    this.setData({
      forms: _forms
    })
  },
  onChangeInput: function(e) {
    console.log("onChangeInput: ", e)
    const id = e.currentTarget.dataset.id
    const pId = e.currentTarget.dataset.pid
    const { forms } = this.data
    const eValue = e.detail
    const _forms = editForm([{pId, id, eValue}], forms)
    this.setData({
      forms: _forms
    })
  },

  openForm: function(e) {
    const id = e.currentTarget.dataset.id
    const forms = this.data.forms
    const _forms = toggleForm(id, forms)
    this.setData({
      forms: _forms
    })
  }

})